//
// Created by konglinglong on 2020/9/8.
//

#include <stdio.h>
#include <iostream>
#include "../lib/doctest.h"
#include "../../include/osal/osMemory.h"

TEST_SUITE ("OS_MEM_TS")
{
    TEST_CASE ("OS_MEM_TC")
    {
        void* ptr;
        uint32_t loop;
        uint32_t loopCnt;
        uint32_t totalSize;

        SUBCASE("OS_MEM_SC_BASE1")
        {
            totalSize = 0;
            loopCnt = rand() % 8192;

            OS_MemResetCounter();

            for (loop = 0; loop < loopCnt; loop++)
            {
                uint32_t size = rand() % 4096 + 8;
                ptr = OS_MemCalloc(1, size);
                REQUIRE(ptr);
                OS_MemFree(ptr);
                totalSize += size;
            }
            REQUIRE(totalSize == OS_MemGetAllocSize());
            REQUIRE(loopCnt == OS_MemGetAllocCount());
            REQUIRE(loopCnt == OS_MemGetFreeCount());
        }

        SUBCASE("OS_MEM_SC_BASE2")
        {
            totalSize = 0;
            loopCnt = rand() % 8192;

            OS_MemResetCounter();

            for (loop = 0; loop < loopCnt; loop++)
            {
                uint32_t size = rand() % 4096 + 8;
                ptr = OS_MemMalloc(size);
                REQUIRE(ptr);
                OS_MemFree(ptr);
                totalSize += size;
            }
            REQUIRE(totalSize == OS_MemGetAllocSize());
            REQUIRE(loopCnt == OS_MemGetAllocCount());
            REQUIRE(loopCnt == OS_MemGetFreeCount());
        }

        SUBCASE("OS_MEM_SC_BASE3")
        {
            totalSize = 0;
            loopCnt = rand() % 8192;

            OS_MemResetCounter();

            for (loop = 0; loop < loopCnt; loop++)
            {
                uint32_t size = rand() % 4096 + 8;
                ptr = OS_MemMalloc(size);
                REQUIRE(ptr);
                ptr = OS_MemRealloc(ptr, size);
                REQUIRE(ptr);
                OS_MemFree(ptr);
                totalSize += size;
            }
            REQUIRE(totalSize == OS_MemGetAllocSize());
            REQUIRE(loopCnt == OS_MemGetAllocCount());
            REQUIRE(loopCnt == OS_MemGetFreeCount());
        }

        SUBCASE("FIX_RB_SC_FUNC")
        {
            char buffer[1024];
            OS_MemDump(buffer, sizeof(buffer));
            printf("%s\n", buffer);
            OS_MemResetCounter();
        }

        REQUIRE(OS_MemGetAllocCount() == OS_MemGetFreeCount());
    }
}
